package com.mk.cloud.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtils {

    private static String getPinYinHeadChar(String zn_str, int caseType) {
        if (zn_str != null && !zn_str.trim().equalsIgnoreCase("")) {
            char[] strChar = zn_str.toCharArray();
            // 汉语拼音格式输出类  
            HanyuPinyinOutputFormat hanYuPinOutputFormat = new HanyuPinyinOutputFormat();
            // 输出设置，大小写，音标方式等  
            if (1 == caseType) {
                hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            } else {
                hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
            }
            hanYuPinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            hanYuPinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
            StringBuffer pyStringBuffer = new StringBuffer();
            for (int i = 0; i < strChar.length; i++) {
                char c = strChar[i];
                char pyc = strChar[i];
                if (String.valueOf(c).matches("[\\u4E00-\\u9FA5]+")) {//是中文或者a-z或者A-Z转换拼音
                    try {
                        String[] pyStirngArray = PinyinHelper.toHanyuPinyinStringArray(strChar[i], hanYuPinOutputFormat);
                        if (null != pyStirngArray && pyStirngArray[0] != null) {
                            pyc = pyStirngArray[0].charAt(0);
                            pyStringBuffer.append(pyc);
                        }
                    } catch (BadHanyuPinyinOutputFormatCombination e) {
                        e.printStackTrace();
                    }
                } else {
                    pyStringBuffer.append(c);
                }
            }
            return pyStringBuffer.toString();
        }
        return null;
    }

    /**
     * 获取大写拼音首字母
     *
     * @param zn_str
     * @return
     */
    public static String getPinYinHeadCharUpperCase(String zn_str) {
        return getPinYinHeadChar(zn_str, 0);
    }

    /**
     * 获取小写拼音首字母
     *
     * @param zn_str
     * @return
     */
    public static String getPinYinHeadCharLowerCase(String zn_str) {
        return getPinYinHeadChar(zn_str, 1);
    }

    public static void main(String[] args) {
//        System.out.println(getPinYinHeadCharUpperCase("嶶姿化妆品店"));
    }

}
